package model

import (
	"context"
	"errors"
	app "im-demo/application"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

// User model
type User struct {
	Id       string `json:"id" form:"id" bson:"_id"`                      // 用户id，直接用mongo的_id
	Username string `json:"username" form:"username" bson:"username"`     // 登录账号
	Password string `json:"password" form:"password" bson:"password"`     // 密码
	Nickname string `json:"nickname" form:"nickname" bson:"nickname"`     // 昵称
	Avator   string `json:"avator,omitempty" form:"avator" bson:"avator"` // 个性化头像
	Sign     string `json:"sign,omitempty" form:"sign" bson:"sign"`       // 签名
}

// SearchUser 搜索用户，用于添加朋友
func SearchUser(ownerId, search string) ([]User, error) {
	objId, err := primitive.ObjectIDFromHex(ownerId)
	if err != nil {
		return nil, err
	}
	filter := bson.M{
		"_id": bson.M{
			"$ne": objId,
		},
		"nickname": search,
	}
	cur, err := app.MongoDBClient.Database(app.MongoDataBaseName).Collection("user").Find(context.TODO(), filter)
	if err != nil {
		return nil, err
	}

	userList := make([]User, 0)
	var user User
	for cur.Next(context.TODO()) {
		err := cur.Decode(&user)
		if err != nil {
			continue
		}
		userList = append(userList, user)
	}

	return userList, nil
}

// GetUserInfo 获取用户信息
func GetUserInfo(ownerId string) (User, error) {
	var user User
	objId, err := primitive.ObjectIDFromHex(ownerId)
	if err != nil {
		return user, err
	}
	err = app.MongoDBClient.Database(app.MongoDataBaseName).Collection("user").FindOne(context.TODO(), bson.M{"_id": objId}).Decode(&user)
	if err != nil {
		return user, err
	}
	return user, nil
}

type RegisterForm struct {
	Username string `json:"username" form:"username" bson:"username"`
	Password string `json:"password" form:"password" bson:"password"`
	Nickname string `json:"nickname" form:"nickname" bson:"nickname"`
	Avator   string `json:"avator,omitempty" form:"avator" bson:"avator"`
	Sign     string `json:"sign,omitempty" form:"sign" bson:"sign"`
}

// Register 注册
func Register(register *RegisterForm) (*mongo.InsertOneResult, error) {
	filter := bson.M{
		"username": register.Username,
	}
	result := app.MongoDBClient.Database(app.MongoDataBaseName).Collection("user").FindOne(context.TODO(), filter)
	if err := result.Err(); err != nil {
		if err == mongo.ErrNoDocuments {
			return app.MongoDBClient.Database(app.MongoDataBaseName).Collection("user").InsertOne(context.TODO(), register)
		}
		return nil, err
	}

	return nil, errors.New("username exist")

}

type LoginForm struct {
	Username string `json:"username" form:"username" bson:"username"`
	Password string `json:"password" form:"password" bson:"password"`
}

// Login 验证登录信息
func Login(filter LoginForm) (User, error) {
	var user User
	err := app.MongoDBClient.Database(app.MongoDataBaseName).Collection("user").FindOne(context.TODO(), filter).Decode(&user)
	if err != nil {
		return user, err
	}
	return user, nil
}
